<?php

namespace app\api\controller;

use think\Controller;
use think\Request;
use think\Db;


class IndiapayController extends Controller
{
    protected function initialize(){
	 	parent::initialize();
		header('Access-Control-Allow-Origin:*');
    }
    public function index(){
       
        
        return $this->fetch();
    }
    
    public function pay(){
        $param = input('param.');
        $amount = (int)$param['price'];
        $accNo = isset($param['accNo']) ? $param['accNo'] : '';
        $bankCode = isset($param['bankCode']) ? $param['bankCode'] : '';
        $orderNo = getSn('IN_');
        $rand_username = rand_username();
        $uid = $param['uid'];
        $userinfo = db('users')->where('id',$uid)->find();
        $data['mer_no'] = config('app.indiapay.mer_no');  
        $data['mer_order_no'] = $orderNo; 
        $data['pname'] = $param['name']; 
        $data['pemail'] =$param['name']."@yahoo.co.in"; 
        $data['phone'] = '91'.rand_phone(); //印尼VOV业务必须填写 VOV注册时的手机号
        $data['order_amount'] = $amount; //必须整数
        $data['countryCode'] = 'IND';   //IDN印尼 IND印度 VNM越南 THA泰国
        $data['ccy_no'] = 'INR';    //IDR印尼卢比INR印度卢比VND越南THB泰铢
        $data['timeout_express'] = '10m'; //订单有效时间  超出自动关闭 m分钟 h小时
        $data['busi_code'] = 'UPI';
        $data['goods'] = "TestGoods"; 
        $data['notifyUrl'] =getHttpType().$_SERVER['HTTP_HOST']."/api/indiapay/notify";
        $data['accNo'] = $accNo;        //银行账户 泰国网银必填
        $data['bankCode'] = $bankCode;     //银行编码 网银业务必填
        $data['pageUrl'] = getHttpType().$_SERVER['HTTP_HOST']."/api/Transaction/getRechargeRecord";
        
        $sign = $this->getSign($data);
        $data['sign'] = $sign;
        //var_dump($data);exit;
        $posturl = config('app.indiapay.post_url')."ty/orderPay";
        $response = $this->send_post($posturl,$data);
        //{"order_no":"2012290000000861001011022070","bankCode":"","mer_no":"gm761100000057012","pname":"ManishaKaniyar","accNo":"","sign":"912d3b0c3f5fe1f9ed6d2604b72b489a","goods":"TestGoods","err_code":"SUCCESS","order_time":"20201229011022","pemail":"manishak891166@yahoo.co.in","phone":"919767445490","order_data":"https://openapi.inpay.cc/order/PAYU_1343620320195645440","countryCode":"IND","err_msg":"Success","order_amount":100,"timeout_express":"10m","notifyUrl":"in.cloudpaymall.com/index/india_pay/notify?order_no=IN_2012290210224533","pageUrl":"in.cloudpaymall.com/index/ctrl/recharge_admin","ccy_no":"INR","busi_code":"UPI","mer_order_no":"IN_2012290210224533","status":"SUCCESS"}
       
       $json = json_decode($response,true);
       if($json['status'] =="SUCCESS"){
            $res = db('user_recharge')->insert([
                'uid'       => $uid,
                'order_number' => $orderNo,
                'type'       => $param['typeid'],
                'bid'       => $param['bid'],
                'money'       => $amount,
                'state'    => 3,
                'add_time'   => time(),
                'postscript'  => $param['name'],
                'bank_code'  => 'IndiaPay'
    
            ]); 
            
            header('Location:'.$json['order_data']);
            exit;
       }else{
           return json(['code'=>1,'info'=>'ERROR_CODE:'.$json['err_code'].",ERROR_MSG:".$json['err_msg']]);
       }
    
    }
    
    private function getSign($data){
        ksort($data);
        $secretKey = config('app.indiapay.secret_key');
        $str='';
        foreach($data as $k=>$v){
            if($v){
                $str.= $k."=".$v."&";
            }
        }
        $sign = md5($str."key=".$secretKey);
        return $sign;
    }
    
    public function send_post($url,$data){
        
        $curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-Type: application/json; charset=utf-8"));
		curl_setopt($curl, CURLOPT_POST, 1);
		curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
		curl_setopt($curl, CURLOPT_TIMEOUT, 300);
		curl_setopt($curl, CURLOPT_HEADER, 0);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		$response = curl_exec($curl);
		$curl_errno = curl_errno($curl);
		$curl_error = curl_error($curl);
		curl_close($curl);
		return $response;
    }
    
    public function notify(){
        $param = input('param.');
        $file = file_put_contents('./india_notify.log',json_encode($param)."\r\n",FILE_APPEND);
        if($param['status']=='SUCCESS'){
            $sign = $param['sign'];
            unset($param['sign']);
            $notifySign = $this->getSign($param);
            if($notifySign == $sign){
                $res = db('user_recharge')->where('order_number',$param['mer_order_no'])->where('state',3)->update(['daozhang_money'=>$param['order_amount'],'endtime'=>time(),'state'=>1]);
                $order = db('user_recharge')->where('order_number',$param['mer_order_no'])->find();
                $is_updata_user = db('user_total')->where('uid' , $order['uid'])->setInc('balance', $param['order_amount'])->setInc('total_recharge',$param['order_amount'])->setInc('total_balance',$param['order_amount']);
                
                
            }else{
                $file = file_put_contents('./india_notify.log',"签名失败"."\r\n",FILE_APPEND);
            }
        }
        die('success');exit;
        
    }
        
    public function payout(){
        $url = config('app.indiapay.post_url')."withdraw/singleOrder";
    }

}